const { app, BrowserWindow, ipcMain, Menu } = require("electron");
const { theme } = require("./unified");

let mainWinId = null;

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    show: false,
    title: theme,
    webPreferences: {
      nodeIntegration: true, // 允许在渲染线程使用nodejs
      contextIsolation: false, // 上下文隔离
      enableRemoteModule: true // 启用远程模块
    }
  });

  win.loadFile(`./${theme}/index.html`);
  mainWinId = win.id;
  win.on("ready-to-show", () => {
    win.show();
  });
  require('@electron/remote/main').initialize(); // 初始化远程功能
  require("@electron/remote/main").enable(win.webContents);
}
app.whenReady().then(() => {
  createWindow();

  // 如果没有窗口打开则打开一个窗口 
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });

  // 关闭所有窗口时退出应用 
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
  });
});

// 接受其他进程的数据
ipcMain.on("openWin2", () => {
  // 接受到点击事件进行创建窗口
  let subWin = new BrowserWindow({
    width: 800,
    height: 600,
    parent: BrowserWindow.fromId(mainWinId),
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    }
  });
  subWin.loadFile(`./${theme}/sub.html`);
  subWin.on("close", () => subWin = null);
});
ipcMain.on("stm", (ev, data) => {
  console.log(data);
  let mainWin = BrowserWindow.fromId(mainWinId);
  mainWin.webContents.send("msgk", data);
});